package com.ys.chatserver.redis;

import com.eva.framework.utils.LoggerFactory;
import com.ys.chatserver.BaseConf;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.time.Duration;
import java.util.HashSet;
import java.util.Set;

public class RedisUtil {
    private static final Logger log = LoggerFactory.getLog();
    //等待可用连接的最大时间，单位毫秒，默认值为-1，表示永不超时。如果超过等待时间，则直接抛出JedisConnectionException；
    private final static int MAX_WAIT = 4 * 1000;
    //超时时间
    private final static int TIMEOUT = 10 * 1000;

    private static JedisPool jedisPool = null;

    /**
     * Jedis实例获取返回码
     */
    public static class JedisStatus {
        /**
         * Jedis实例获取失败
         */
        public static final long FAIL_LONG = -5L;
        /**
         * Jedis实例获取失败
         */
        public static final int FAIL_INT = -5;
        /**
         * Jedis实例获取失败
         */
        public static final String FAIL_STRING = "-5";
    }

    private static void initialPool() {
        //Redis服务器IP
        String HOST = BaseConf.getInstance().getREDIS_SERVER_IP();
        //Redis的端口号
        int PORT = Integer.parseInt(BaseConf.getInstance().getREDIS_SERVER_PORT());
        //访问密码
        String AUTH = BaseConf.getInstance().getREDIS_LOGIN_PASSWORD();
        // 数据库
        Integer DATABASE = BaseConf.getInstance().getREDIS_DATABASE();

        try {
            JedisPoolConfig config = new JedisPoolConfig();
            //最大连接数，如果赋值为-1，则表示不限制；如果pool已经分
            // 配了maxActive个jedis实例，则此时pool的状态为exhausted(耗尽)。
            config.setMaxTotal(64);
            //最大空闲数，控制一个pool最多有多少个状态为idle(空闲的)的jedis实例，默认值也是8。
            config.setMaxIdle(50);
            //最小空闲数
            config.setMinIdle(5);
            //是否在从池中取出连接前进行检验，如果检验失败，则从池中去除连接并尝试取出另一个
            config.setTestOnBorrow(false);
            //在return给pool时，是否提前进行validate操作
            config.setTestOnReturn(false);
            //表示一个对象至少停留在idle状态的最短时间，然后才能被idle object evitor扫描并驱逐；
            //这一项只有在timeBetweenEvictionRunsMillis大于0时才有意义
            config.setMinEvictableIdleTimeMillis(30000);
            //表示idle object evitor两次扫描之间要sleep的毫秒数
            config.setTimeBetweenEvictionRunsMillis(10000);
            //表示idle object evitor每次扫描的最多的对象数
            config.setNumTestsPerEvictionRun(-1);
            //等待可用连接的最大时间，单位毫秒，默认值为-1，表示永不超时。如果超过等待时间，则直接抛出JedisConnectionException；
            config.setMaxWaitMillis(MAX_WAIT);

            jedisPool = new JedisPool(config, HOST, PORT, TIMEOUT, StringUtils.isNotBlank(AUTH) ? AUTH : null, DATABASE, null);

        } catch (Exception e) {
            if (jedisPool != null) {
                jedisPool.close();
            }
            log.error("初始化Redis连接池失败", e);
        }
    }

    /**
     * 初始化Redis连接池
     */
    static {
        initialPool();
    }

    /**
     * 在多线程环境同步初始化
     */
    private static synchronized void poolInit() {
        if (jedisPool == null) {
            initialPool();
        }
    }


    /**
     * 同步获取Jedis实例
     */
    public static Jedis getJedis() {
        if (jedisPool == null) {
            poolInit();
        }
        Jedis jedis = null;
        try {
            if (jedisPool != null) {
                jedis = jedisPool.getResource();
            }
        } catch (Exception e) {
            log.error("同步获取Jedis实例失败" + e.getMessage(), e);
            returnBrokenResource(jedis);
        }
        return jedis;
    }

    /**
     * 释放jedis资源
     */
    public static void returnResource(final Jedis jedis) {
        if (jedis != null && jedisPool != null) {
            jedis.close();
        }
    }

    public static void returnBrokenResource(final Jedis jedis) {
        if (jedis != null && jedisPool != null) {
            jedis.close();
        }
    }

    /**
     * 设置值
     *
     * @return -5：Jedis实例获取失败<br/>OK：操作成功<br/>null：操作失败
     */
    public static String set(String key, String value) {
        Jedis jedis = getJedis();
        if (jedis == null) {
            return JedisStatus.FAIL_STRING;
        }
        String result = null;
        try {
            result = jedis.set(key, value);
        } finally {
            returnResource(jedis);
        }
        return result;
    }

    /**
     * 设置值
     *
     * @param expire 过期时间，单位：秒
     * @return -5：Jedis实例获取失败<br/>OK：操作成功<br/>null：操作失败
     */
    public static String set(String key, String value, long expire) {
        Jedis jedis = getJedis();
        if (jedis == null) {
            return JedisStatus.FAIL_STRING;
        }
        String result = null;
        try {
            result = jedis.setex(key, expire, value);
        } finally {
            returnResource(jedis);
        }
        return result;
    }

    /**
     * 获取值
     */
    public static String get(String key) {
        Jedis jedis = getJedis();
        if (jedis == null) {
            return JedisStatus.FAIL_STRING;
        }
        String result = null;
        try {
            result = jedis.get(key);
        } finally {
            returnResource(jedis);
        }
        return result;
    }

    /**
     * 设置key的过期时间
     */
    public static long expire(String key, int seconds) {
        Jedis jedis = getJedis();
        if (jedis == null) {
            return JedisStatus.FAIL_LONG;
        }
        long result = 0;
        try {
            result = jedis.expire(key, seconds);
        } finally {
            returnResource(jedis);
        }

        return result;
    }

    public static boolean exists(String key) {
        Jedis jedis = getJedis();
        if (jedis == null) {
            log.warn("Jedis实例获取为空");
            return false;
        }
        boolean result = false;
        try {
            result = jedis.exists(key);
        } finally {
            returnResource(jedis);
        }
        return result;
    }

    /**
     * 删除key
     *
     * @return -5：Jedis实例获取失败，1：成功，0：失败
     */
    public static long del(String... keys) {
        Jedis jedis = getJedis();
        if (jedis == null) {
            return JedisStatus.FAIL_LONG;
        }
        long result = JedisStatus.FAIL_LONG;
        try {
            result = jedis.del(keys);
        } finally {
            returnResource(jedis);
        }
        return result;
    }

    /**
     * set if not exists，若key已存在，则setnx不做任何操作
     *
     * @param value key已存在，1：key赋值成功
     */
    public static long setnx(String key, String value) {
        long result = JedisStatus.FAIL_LONG;
        Jedis jedis = getJedis();
        if (jedis == null) {
            return result;
        }
        try {
            result = jedis.setnx(key, value);
        } finally {
            returnResource(jedis);
        }
        return result;
    }

    /**
     * set if not exists，若key已存在，则setnx不做任何操作
     *
     * @param value  key已存在，1：key赋值成功
     * @param expire 过期时间，单位：秒
     */
    public static long setnx(String key, String value, int expire) {
        long result = JedisStatus.FAIL_LONG;
        Jedis jedis = getJedis();
        if (jedis == null) {
            return result;
        }
        try {
            result = jedis.setnx(key, value);
            jedis.expire(key, expire);
        } finally {
            returnResource(jedis);
        }
        return result;
    }

    public static Set<String> keys(String pattern) {
        Set<String> keyList = new HashSet<String>();
        Jedis jedis = getJedis();
        if (jedis == null) {
            log.warn("Jedis实例获取为空");
            return keyList;
        }
        try {
            keyList = jedis.keys(pattern);
        } finally {
            returnResource(jedis);
        }
        return keyList;
    }
}